package cn.com.surker.sale.service.impl;

import cn.com.surker.base.strength.dao.BaseStrengthDao;
import cn.com.surker.base.strength.dao.BaseStrengthLevelDao;
import cn.com.surker.base.strength.dao.BaseStrengthOrgDao;
import cn.com.surker.base.strength.entity.BaseStrength;
import cn.com.surker.base.strength.entity.BaseStrengthLevel;
import cn.com.surker.base.strength.entity.BaseStrengthOrg;
import cn.com.surker.common.Code;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.enums.sale.SpecialPriceTypeEnum;
import cn.com.surker.sale.dao.SaleContractDao;
import cn.com.surker.sale.dao.SaleContractStrengthPriceDao;
import cn.com.surker.sale.dao.SaleStrengthSpecialPriceDao;
import cn.com.surker.sale.entity.SaleContract;
import cn.com.surker.sale.entity.SaleContractStrengthPrice;
import cn.com.surker.sale.service.SaleContractStrengthPriceBaseService;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.dao.*;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.entity.SysMessageRecord;
import cn.com.surker.system.entity.SysOrigin;
import cn.com.surker.system.entity.SysUser;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.vo.sale.SaleContractVo;
import cn.com.surker.vo.sale.SaleStrengthSpecialPriceVo;
import cn.com.surker.wechat.WechatOaGroupApi;
import cn.com.surker.wechat.WechatSurkerGroupApi;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * @Author lucky
 * @create 2024年07月09 15:43
 * @desc
 */
public abstract class SaleContractStrengthPriceBaseServiceImpl extends ServiceImpl<SaleContractStrengthPriceDao, SaleContractStrengthPrice> implements SaleContractStrengthPriceBaseService {

    @Resource
    protected DataSourceInfoDao dataSourceInfoDao;
    @Resource
    protected SaleContractDao saleContractDao;
    @Resource
    protected BaseStrengthDao baseStrengthDao;
    @Resource
    protected BaseStrengthLevelDao baseStrengthLevelDao;
    @Resource
    protected BaseStrengthOrgDao baseStrengthOrgDao;
    @Resource
    protected SaleContractStrengthPriceDao saleContractStrengthPriceDao;
    @Resource
    protected SaleStrengthSpecialPriceDao saleStrengthSpecialPriceDao;
    @Resource
    private SysMessageRecordDao messageRecordDao;
    @Resource
    private SysUserPositionDao userPositionDao;
    @Resource
    private SysUserDao userDao;
    @Resource
    private SysOriginDao originDao;

    /**
     * 根据生效时间查询标号
     * @param contractId
     * @param takeTime
     * @return
     */
    public List<SaleContractStrengthPrice> findByTakeTime(Long contractId, String takeTime) {
        if (StringUtils.isAllParamNull(contractId, takeTime))
            return null;
        QueryWrapper<SaleContractStrengthPrice> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("take_time", takeTime);
        query.eq("contract_id", contractId);
        List<SaleContractStrengthPrice> list = saleContractStrengthPriceDao.selectList(query);
        if (list == null || list.size() == 0)
            return null;
        return list;
    }

    /**
     * 查询销售合同砼单价信息
     * @param contractId
     * @return
     */
    @Override
    public Map<String, List<SaleContractStrengthPrice>> findByContract(Long contractId) {
        if (StringUtils.isNull(contractId))
            return null;
        QueryWrapper<SaleContractStrengthPrice> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("contract_id", contractId);
        query.orderByDesc("take_time");
        List<SaleContractStrengthPrice> priceList = saleContractStrengthPriceDao.selectList(query);
        if (priceList == null || priceList.size() == 0)
            return null;
        Map<String, List<SaleContractStrengthPrice>> map = new LinkedHashMap<>();
        for (int i = 0; i < priceList.size(); i++) {
            SaleContractStrengthPrice price = priceList.get(i);
            String takeTime = DateUtil.convertString(price.getTakeTime());
            if (map.containsKey(takeTime)) {
                List<SaleContractStrengthPrice> tempList = map.get(takeTime);
                tempList.add(price);
                map.put(takeTime, tempList);
            } else {
                List<SaleContractStrengthPrice> tempList = new ArrayList<>();
                tempList.add(price);
                map.put(takeTime, tempList);
            }
        }
        return map;
    }
    /**
     * 新增砼单价信息
     * @param orgId
     * @param contractId 合同ID
     * @param strengthId 砼标号
     * @param price 单价
     * @param takeTime 生效时间
     * @param remark
     * @param creator
     * @return
     */
    @Override
    public Integer saveStrength(Long orgId, Long contractId, Long strengthId, Double price, Double taxPrice, String takeTime,
                        String remark, String creator) {
        if (StringUtils.isAllParamNull(orgId, contractId, strengthId, price, takeTime))
            return Code.PARAM_EMPTY.getCode();
        if (price < 1)
            return Code.PRICE_LT1.getCode();
        Date nowDate = new Date();
        Date takeDate = DateUtil.convertDate(takeTime);
        taxPrice = price;
        DataSourceInfo ds = dataSourceInfoDao.queryDSByOriginId(orgId);
        if (ds == null || ds.getStatus() == 1)
            return Code.STATION_ERROR.getCode();

        SaleContractVo saleContract = saleContractDao.selectById(contractId);
        if (StringUtils.isNull(orgId))
            orgId =saleContract.getOrgId();
        if (saleContract == null)
            return Code.CONTRACT_EMPTY.getCode();

        SaleContractStrengthPrice sp = saleContractStrengthPriceDao.findTakeTime(orgId, contractId, strengthId, takeDate);
        if (sp != null) {
            sp.setStrengthId(strengthId);
            sp.setRemark(remark);
            sp.setBeforePrice(sp.getPrice());
            sp.setTaxPrice(sp.getPrice());
            sp.setPrice(price);
            sp.setUpdator(creator);
            sp.setUpdateTime(nowDate);
            Integer code = saleContractStrengthPriceDao.updateById(sp);
            if (code > 0) {
                try {
                    sendMessage(saleContract, strengthId, DateUtil.convertString(sp.getTakeTime()), sp.getPrice(),
                            price,sp.getTaxPrice(), taxPrice, StringUtils.convertString(sp.getRemark()), creator,1);
                } catch (Exception e) {
                    log.error("更新标号消息推送错误" + e.getMessage());
                }
                return 0;
            }
            return -1;
        }

        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthId, orgId);
        if (strengthOrg == null ) {
            BaseStrength strength = baseStrengthDao.selectById(strengthId);
            if (strength == null)
                return Code.LEVEL_EMPTY.getCode();
            String strengthSql = "insert into Sys_ConcreteStrength_T (Sys_Dept_ID,CompressiveStrength,Anti_permeabilityLevel,\n" +
                    "  BendingLevel,Anti_freezeLevel,MaterialRequirements,TechRequirements,StrengthLevel,Remarks,CreatorID,\n" +
                    "  CreationTime,IsValid,Dosage,IsNormal) " +
                    "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            String sql = "select top 1 * from Sys_ConcreteStrength_T where StrengthLevel = '" + strength.getStrength() + "' and IsValid = 1";

            long taskId = 0l;
            if (ds.getType() == 1) {
                List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql);
                if (listMap == null || listMap.size() == 0) {
                    Object[] params = {1, strength.getLevel(), strength.getPermeability(), strength.getBending(), strength.getFreeze(),
                            strength.getMaterialRequirement(), strength.getTechnologyRequirement(), strength.getStrength(), "", 1,
                            DateUtil.convertString(nowDate), 1, strength.getDosage(), 0};

                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(new PreparedStatementCreator() {
                        @Override
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement ps = connection.prepareStatement(strengthSql, new String[]{"ID"});
                            for (int i = 0; i < params.length; i++) {
                                ps.setObject(i + 1, params[i]);
                            }
                            return ps;
                        }
                    }, keyHolder);
                    taskId = keyHolder.getKey().longValue();
                    if (taskId < 1) {
                        return -1;
                    }
                } else {
                    taskId = StringUtils.convertLong(listMap.get(0).get("ID"));
                }
            }

            strengthOrg = new BaseStrengthOrg(orgId, taskId, strengthId, 0, "", creator, nowDate);
            strengthOrg.setTransportType(strength.getTransportType());
            baseStrengthOrgDao.insert(strengthOrg);
            try {
                sendLabMessage(saleContract, strength.getStrength(), DateUtil.convertString(nowDate), remark, creator);
            } catch (Exception e) {
                log.error("推送新增标号预警异常" + e.getMessage());
            }
        }
        Long erpId = null;
        if (!StringUtils.isNull(saleContract.getErpid()) && saleContract.getErpid() > 0) {
            erpId = saleContract.getErpid();
        } else {
            if (ds.getType() == 1) {
                String contractSql = "select top 1 * from market_contract_t " +
                        " where isvalid = 1 and U_Code = '" + saleContract.getCode() + "' order by id desc";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(contractSql);
                if (list == null || list.size() == 0)
                    return Code.ERP_CONTRACT_EMPTY.getCode();
                erpId = StringUtils.convertLong(list.get(0).get("ID"));
            }

        }
        if (ds.getType() == 1) {
            long taskId = saveOrUpdateErp(jdbcTemplate, erpId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                    price, remark, nowDate, 0,0);
        }

        SaleContractStrengthPrice strengthPrice = new SaleContractStrengthPrice(orgId, contractId, strengthId,
                price, takeDate, 0, remark, creator, nowDate);
        strengthPrice.setTaxPrice(taxPrice);
        Integer code = saleContractStrengthPriceDao.insert(strengthPrice);

        if (code > 0) {
            try {
                sendMessage(saleContract, strengthId, takeTime, price,
                        null, taxPrice, null, remark, creator, 0);
            } catch (Exception e) {
                log.error("推送修改标号消息异常" + e.getMessage());
            }
            return 0;
        }

        return -1;
    }

    /**
     * 修改合同
     * @param id
     * @param strengthId 砼标号
     * @param price 单价
     * @param takeTime 生效时间
     * @param remark
     * @param creator
     * @return
     */
    @Override
    public Integer updateStrength(Long id, Long strengthId, Double price, Double taxPrice, String takeTime,
                                  String remark, String creator) {
        if (StringUtils.isNull(id))
            return Code.PARAM_EMPTY.getCode();
        SaleContractStrengthPrice strengthPrice = saleContractStrengthPriceDao.selectById(id);
        Date nowDate = new Date();
        taxPrice = price;
        if (strengthPrice == null || strengthPrice.getStatus() == 1)
            return Code.ERROR_DATA.getCode();
        SaleContractStrengthPrice newStrengthPrice = new SaleContractStrengthPrice();
        if (!StringUtils.isNull(price) && price > 0) {
            newStrengthPrice.setBeforePrice(strengthPrice.getPrice());
            newStrengthPrice.setPrice(price);
        }
        if (!StringUtils.isNull(takeTime)) {
            Date takeDate = DateUtil.convertDate(takeTime);
            newStrengthPrice.setTakeTime(takeDate);
        }
        if (!StringUtils.isNull(strengthId))
            newStrengthPrice.setStrengthId(strengthId);
        if (!StringUtils.isNull(remark))
            newStrengthPrice.setRemark(remark);
        newStrengthPrice.setUpdateTime(nowDate);
        newStrengthPrice.setUpdator(creator);
        newStrengthPrice.setId(strengthPrice.getId());
        Integer code = saleContractStrengthPriceDao.updateById(newStrengthPrice);
        if (code > 0) {
            SaleContractVo contract = saleContractDao.selectById(strengthPrice.getContractId());
            if (!StringUtils.isNull(price) && price > 0) {
                try {
                    sendMessage(contract, strengthId, DateUtil.convertString(newStrengthPrice.getTakeTime()), strengthPrice.getPrice(),
                            price, strengthPrice.getTaxPrice(), taxPrice, StringUtils.convertString(newStrengthPrice.getRemark()), creator,1);
                } catch (Exception e) {
                    log.error("推送修改标号消息异常" + e.getMessage());
                }
            }

            if (contract == null || StringUtils.isNull(contract.getErpid()))
                return 0;
            DataSourceInfo ds = dataSourceInfoDao.queryDSByOriginId(contract.getOrgId());
            if (ds == null || ds.getStatus() == 1)
                return Code.STATION_ERROR.getCode();
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
            BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthPrice.getStrengthId(), contract.getOrgId());
            if (strengthOrg == null ) {
                String strengthSql = "insert into Sys_ConcreteStrength_T (Sys_Dept_ID,CompressiveStrength,Anti_permeabilityLevel,\n" +
                        "  BendingLevel,Anti_freezeLevel,MaterialRequirements,TechRequirements,StrengthLevel,Remarks,CreatorID,\n" +
                        "  CreationTime,IsValid,Dosage,IsNormal) " +
                        "values(?,?,?,?,?,?,?,?,?,?,?,?,2350,?)";
                BaseStrength strength = baseStrengthDao.selectById(id);
                if (strength == null)
                    return Code.LEVEL_EMPTY.getCode();
                long taskId = 0l;
                if (ds.getType() == 1) {
                    String sql = "select top 1 * from Sys_ConcreteStrength_T where StrengthLevel = '" + strength.getStrength() + "' and IsValid = 1";
                    List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql);
                    if (listMap == null || listMap.size() == 0) {
                        Object[] params = {1, strength.getLevel(), strength.getPermeability(), strength.getBending(), strength.getFreeze(),
                                strength.getMaterialRequirement(), strength.getTechnologyRequirement(), strength.getStrength(), "", 1,
                                DateUtil.convertString(nowDate), 1, strength.getDosage(), 0};

                        KeyHolder keyHolder = new GeneratedKeyHolder();
                        jdbcTemplate.update(new PreparedStatementCreator() {
                            @Override
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                PreparedStatement ps = connection.prepareStatement(strengthSql, new String[]{"ID"});
                                for (int i = 0; i < params.length; i++) {
                                    ps.setObject(i + 1, params[i]);
                                }
                                return ps;
                            }
                        }, keyHolder);
                        taskId = keyHolder.getKey().longValue();
                        if (taskId < 1) {
                            return -1;
                        }
                    } else {
                        taskId = StringUtils.convertLong(listMap.get(0).get("ID"));
                    }
                }

                strengthOrg = new BaseStrengthOrg(contract.getOrgId(), taskId, id, 0, "", creator, nowDate);
                strengthOrg.setTransportType(strength.getTransportType());
                baseStrengthOrgDao.insert(strengthOrg);
                try {
                    sendLabMessage(contract, strength.getStrength(), DateUtil.convertString(nowDate), remark, creator);
                } catch (Exception e) {
                    log.error("推送新增标号预警异常" + e.getMessage());
                }
            }
            Long erpId = null;
            if (!StringUtils.isNull(contract.getErpid()) && contract.getErpid() > 0) {
                erpId = contract.getErpid();
            } else {
                if (ds.getType() == 1) {
                    String contractSql = "select top 1 * from market_contract_t " +
                            " where isvalid = 1 and U_Code = '" + contract.getCode() + "' order by id desc";
                    List<Map<String, Object>> list = jdbcTemplate.queryForList(contractSql);
                    if (list == null || list.size() == 0)
                        return Code.ERP_CONTRACT_EMPTY.getCode();
                    erpId = StringUtils.convertLong(list.get(0).get("ID"));
                }
            }
            saveOrUpdateErp(jdbcTemplate, erpId, strengthOrg.getErpId(), DateUtil.convertString(strengthPrice.getTakeTime()),
                    price, remark, nowDate, 0, 1);
            return 0;
        }
        return -1;
    }

    /**
     * 禁用合同
     * @param id
     * @param status
     * @return
     */
    @Override
    public Integer updateStatus(Long id, Integer status, String creator) {
        if (StringUtils.isNull(id))
            return Code.PARAM_EMPTY.getCode();
        SaleContractStrengthPrice strengthPrice = saleContractStrengthPriceDao.selectById(id);
        Date nowDate = new Date();
        if (strengthPrice == null)
            return Code.ERROR_DATA.getCode();
        strengthPrice.setStatus(status);
        strengthPrice.setUpdateTime(nowDate);
        strengthPrice.setUpdator(creator);
        Integer code = saleContractStrengthPriceDao.updateById(strengthPrice);
        if (code > 0) {
            SaleContractVo contract = saleContractDao.selectById(strengthPrice.getContractId());
            if (contract == null || StringUtils.isNull(contract.getErpid()))
                return 0;
            DataSourceInfo ds = dataSourceInfoDao.queryDSByOriginId(contract.getOrgId());
            long taskId = 0l;
            BaseStrength strength = baseStrengthDao.selectById(strengthPrice.getStrengthId());
            if (strength == null)
                return Code.LEVEL_EMPTY.getCode();
            if (ds == null || ds.getStatus() == 1)
                return Code.STATION_ERROR.getCode();
            BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthPrice.getStrengthId(), contract.getOrgId());
            if (ds.getType() == 1) {
                JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
                Long strengthErpId = strengthOrg.getErpId();
                if (strengthOrg == null || StringUtils.isNull(strengthOrg.getErpId())) {
                    String strengthSql = "insert into Sys_ConcreteStrength_T (Sys_Dept_ID,CompressiveStrength,Anti_permeabilityLevel,\n" +
                            "  BendingLevel,Anti_freezeLevel,MaterialRequirements,TechRequirements,StrengthLevel,Remarks,CreatorID,\n" +
                            "  CreationTime,IsValid,Dosage,IsNormal) " +
                            "values(?,?,?,?,?,?,?,?,?,?,?,?,2350,?)";
                    String sql = "select top 1 * from Sys_ConcreteStrength_T where StrengthLevel = '" + strength.getStrength() + "' and IsValid = 1";
                    List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql);
                    if (listMap == null || listMap.size() == 0) {
                        strength.setDosage(2350.0);
                        Object[] params = {1, strength.getLevel(), strength.getPermeability(), strength.getBending(), strength.getFreeze(),
                                strength.getMaterialRequirement(), strength.getTechnologyRequirement(), strength.getStrength(), "", 1,
                                DateUtil.convertString(nowDate), 1, strength.getDosage(), 0};

                        KeyHolder keyHolder = new GeneratedKeyHolder();
                        jdbcTemplate.update(new PreparedStatementCreator() {
                            @Override
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                PreparedStatement ps = connection.prepareStatement(strengthSql, new String[]{"ID"});
                                for (int i = 0; i < params.length; i++) {
                                    ps.setObject(i + 1, params[i]);
                                }
                                return ps;
                            }
                        }, keyHolder);
                        taskId = keyHolder.getKey().longValue();
                        if (taskId < 1) {
                            return -1;
                        }
                    } else {
                        taskId = StringUtils.convertLong(listMap.get(0).get("ID"));
                    }

                    strengthErpId = taskId;
                }
                String sql = "select top 1 * from Market_Contract_Price_T where IsValid = 1 and Market_Contract_ID = "
                        + contract.getErpid() + " and Sys_ConcreteStrength_ID = " + strengthErpId + " and StartDatetime = '"
                        + DateUtil.convertString(strengthPrice.getTakeTime()) + "'";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
                if (list != null && list.size() > 0) {
                    Integer isValid = 1;
                    if (status == 1)
                        isValid = 0;
                    sql = "update Market_Contract_Price_T set IsValid = " + isValid + " where id = " + list.get(0).get("ID");
                    jdbcTemplate.update(sql);
                }
            }

            try {
                sendLabMessage(contract, strength.getStrength(), DateUtil.convertString(nowDate), "标号启用更新", creator);
            } catch (Exception e) {
                log.error("推送新增标号预警异常" + e.getMessage());
            }
            if (strengthOrg == null) {
                strengthOrg = new BaseStrengthOrg(contract.getOrgId(), taskId, id, 0, "", creator, nowDate);
                strengthOrg.setTransportType(strength.getTransportType());
                baseStrengthOrgDao.insert(strengthOrg);
            }

            return 0;
        }
        return -1;
    }

    /**
     * 批量新增砼单价
     * @param strengthList
     * @return
     */
    public Integer saveBatchStrength(List<SaleContractStrengthPrice> strengthList, Long orgId,
                                 Long contractId, String creator) {
        if (strengthList == null || strengthList.size() == 0)
            return 0;
        List<SaleContractStrengthPrice> tempList = new ArrayList<>();
        DataSourceInfo ds = dataSourceInfoDao.queryDSByOriginId(orgId);
        if (ds == null || ds.getStatus() == 1)
            return Code.STATION_ERROR.getCode();
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        SaleContractVo saleContract = saleContractDao.selectById(contractId);
        if (saleContract == null)
            return Code.CONTRACT_EMPTY.getCode();
        if (StringUtils.isNull(orgId))
            orgId =saleContract.getOrgId();
        Long erpConId = saleContract.getErpid();
        Date nowDate = new Date();
        for (int i = 0; i < strengthList.size(); i++) {
            SaleContractStrengthPrice contractStrengthPrice = strengthList.get(i);
            Long strengthId = contractStrengthPrice.getStrengthId();
            Double price = contractStrengthPrice.getPrice();
            Date takeDate = contractStrengthPrice.getTakeTime();
            String remark = contractStrengthPrice.getRemark();
            Integer status = contractStrengthPrice.getStatus();
            contractStrengthPrice.setOrgId(orgId);
			if (status == null) {
				contractStrengthPrice.setStatus(StateEnum.ENABLED.getCode());
				status = StateEnum.ENABLED.getCode();
			}
            contractStrengthPrice.setContractId(contractId);
            if (StringUtils.isNull(status))
                status = 0;
            if (StringUtils.isAllParamNull(orgId, contractId, strengthId, price, takeDate))
                continue;
            if (price < 1)
                price = 1.0;
            SaleContractStrengthPrice sp = saleContractStrengthPriceDao.findTakeTime(orgId, contractId, strengthId, takeDate);
            if (sp != null) {//标号与时间已存在
                sp.setPrice(price);
                sp.setStrengthId(strengthId);
                sp.setRemark(remark);
                sp.setUpdator(creator);
                sp.setUpdateTime(nowDate);
                tempList.add(sp);
                try {
                    BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthId, orgId);
                    if (strengthOrg != null) {
                        saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                                price, remark, nowDate, 0, 1);
                    }
                } catch (Exception e) {
                    log.error("更新标号异常" + e.getMessage());
                }
                continue;
            }
            BaseStrength strength = baseStrengthDao.selectById(strengthId);
            if (strength == null)
                continue;
            long taskId = 0l;
            BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthId, orgId);
            if (strengthOrg == null ) {
                if (ds.getType() == 1) {
                    String strengthSql = "insert into Sys_ConcreteStrength_T (Sys_Dept_ID,CompressiveStrength,Anti_permeabilityLevel,\n" +
                            "  BendingLevel,Anti_freezeLevel,MaterialRequirements,TechRequirements,StrengthLevel,Remarks,CreatorID,\n" +
                            "  CreationTime,IsValid,Dosage,IsNormal) " +
                            "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    String sql = "select top 1 * from Sys_ConcreteStrength_T where StrengthLevel = '" + strength.getStrength() + "' and IsValid = 1";
                    List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql);
                    if (listMap == null || listMap.size() == 0) {
                        strength.setDosage(2350.0);
                        Object[] params = {1, strength.getLevel(), strength.getPermeability(), strength.getBending(), strength.getFreeze(),
                                strength.getMaterialRequirement(), strength.getTechnologyRequirement(), strength.getStrength(), "", 1,
                                DateUtil.convertString(nowDate), 1, strength.getDosage(), 0};

                        KeyHolder keyHolder = new GeneratedKeyHolder();
                        jdbcTemplate.update(new PreparedStatementCreator() {
                            @Override
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                PreparedStatement ps = connection.prepareStatement(strengthSql, new String[]{"ID"});
                                for (int i = 0; i < params.length; i++) {
                                    ps.setObject(i + 1, params[i]);
                                }
                                return ps;
                            }
                        }, keyHolder);
                        taskId = keyHolder.getKey().longValue();
                        if (taskId < 1) {
                            continue;
                        }
                    } else {
                        taskId = StringUtils.convertLong(listMap.get(0).get("ID"));
                    }
                }

                strengthOrg = new BaseStrengthOrg(saleContract.getOrgId(), taskId, strengthId, 0, "", creator, nowDate);
                strengthOrg.setTransportType(strength.getTransportType());
                baseStrengthOrgDao.insert(strengthOrg);
                try {
                    sendLabMessage(saleContract, strength.getStrength(), DateUtil.convertString(nowDate), remark, creator);
                } catch (Exception e) {
                    log.error("推送新增标号预警异常" + e.getMessage());
                }
            }
            if (status == 0) {
                if (ds.getType() == 1) {
                    if (StringUtils.isNull(contractStrengthPrice.getId())) {
                        taskId = saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                                price, remark, nowDate, 0, 0);
                        if (taskId < 1) {
                            return -1;
                        }
                    } else {
                        taskId = saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                                price, remark, nowDate, 0, 1);
                        if (taskId < 1) {
                            continue;
                        }
                    }
                }

                contractStrengthPrice.setContractId(contractId);
                contractStrengthPrice.setCreateTime(nowDate);
                contractStrengthPrice.setCreator(creator);
            } else {
                if (ds.getType() == 1) {
                    taskId = saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                            price, remark, nowDate, 1, 1);
                    if (taskId < 1) {
                        return -1;
                    }
                }
                contractStrengthPrice.setContractId(contractId);
                contractStrengthPrice.setUpdator(creator);
                contractStrengthPrice.setUpdateTime(nowDate);
            }
            tempList.add(contractStrengthPrice);
        }
        if (tempList == null || tempList.size() == 0)
            return -1;
        Integer code = saleContractStrengthPriceDao.saveBatch(tempList);
        if (code > 0) {
            return 0;
        }
        return -1;
    }
    public Integer saveBatchStrengthV1(List<SaleContractStrengthPrice> strengthList, String takeTime, Long orgId,
                                     Long contractId, String creator) {
        if (strengthList == null || strengthList.size() == 0)
            return 0;
        List<SaleContractStrengthPrice> tempList = new ArrayList<>();
        DataSourceInfo ds = dataSourceInfoDao.queryDSByOriginId(orgId);
        if (ds == null || ds.getStatus() == 1)
            return Code.STATION_ERROR.getCode();
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        SaleContractVo saleContract = saleContractDao.selectById(contractId);
        if (StringUtils.isNull(orgId))
            orgId =saleContract.getOrgId();
        if (saleContract == null)
            return Code.CONTRACT_EMPTY.getCode();
        Long erpConId = saleContract.getErpid();
        Date nowDate = new Date();
        for (int i = 0; i < strengthList.size(); i++) {
            SaleContractStrengthPrice contractStrengthPrice = strengthList.get(i);
            Long strengthId = contractStrengthPrice.getStrengthId();
            Double price = contractStrengthPrice.getPrice();
            Date takeDate = DateUtil.convertDate(takeTime);
            String remark = contractStrengthPrice.getRemark();
            Integer status = contractStrengthPrice.getStatus();
            contractStrengthPrice.setOrgId(orgId);
            if (status == null) {
                contractStrengthPrice.setStatus(StateEnum.ENABLED.getCode());
                status = StateEnum.ENABLED.getCode();
            }
            contractStrengthPrice.setContractId(contractId);
            if (StringUtils.isNull(status))
                status = 0;
            if (StringUtils.isAllParamNull(orgId, contractId, strengthId, price, takeDate))
                continue;
            if (price < 1)
                price = 1.0;
            SaleContractStrengthPrice sp = saleContractStrengthPriceDao.findTakeTime(orgId, contractId, strengthId, takeDate);
            if (sp != null) {//标号与时间已存在
                sp.setPrice(price);
                sp.setStrengthId(strengthId);
                sp.setRemark(remark);
                sp.setUpdator(creator);
                sp.setUpdateTime(nowDate);
                tempList.add(sp);
                try {
                    BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthId, orgId);
                    if (strengthOrg != null) {
                        saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                                price, remark, nowDate, 0, 1);
                    }
                } catch (Exception e) {
                    log.error("更新标号异常" + e.getMessage());
                }
                continue;
            }
            long taskId = 0l;
            BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strengthId, orgId);
            if (strengthOrg == null ) {
                BaseStrength strength = baseStrengthDao.selectById(strengthId);
                if (strength == null)
                    continue;
                if (ds.getType() == 1) {
                    String strengthSql = "insert into Sys_ConcreteStrength_T (Sys_Dept_ID,CompressiveStrength,Anti_permeabilityLevel,\n" +
                            "  BendingLevel,Anti_freezeLevel,MaterialRequirements,TechRequirements,StrengthLevel,Remarks,CreatorID,\n" +
                            "  CreationTime,IsValid,Dosage,IsNormal) " +
                            "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    String sql = "select top 1 * from Sys_ConcreteStrength_T where StrengthLevel = '" + strength.getStrength() + "' and IsValid = 1";
                    List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql);
                    if (listMap == null || listMap.size() == 0) {
                        strength.setDosage(2350.0);
                        Object[] params = {1, strength.getLevel(), strength.getPermeability(), strength.getBending(), strength.getFreeze(),
                                strength.getMaterialRequirement(), strength.getTechnologyRequirement(), strength.getStrength(), "", 1,
                                DateUtil.convertString(nowDate), 1, strength.getDosage(), 0};

                        KeyHolder keyHolder = new GeneratedKeyHolder();
                        jdbcTemplate.update(new PreparedStatementCreator() {
                            @Override
                            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                                PreparedStatement ps = connection.prepareStatement(strengthSql, new String[]{"ID"});
                                for (int i = 0; i < params.length; i++) {
                                    ps.setObject(i + 1, params[i]);
                                }
                                return ps;
                            }
                        }, keyHolder);
                        taskId = keyHolder.getKey().longValue();
                        if (taskId < 1) {
                            return -1;
                        }
                    } else {
                        taskId = StringUtils.convertLong(listMap.get(0).get("ID"));
                    }
                }

                strengthOrg = new BaseStrengthOrg(saleContract.getOrgId(), taskId, strengthId, 0, "", creator, nowDate);
                strengthOrg.setTransportType(strength.getTransportType());
                baseStrengthOrgDao.insert(strengthOrg);
                try {
                    sendLabMessage(saleContract, strength.getStrength(), DateUtil.convertString(nowDate), remark, creator);
                } catch (Exception e) {
                    log.error("推送新增标号预警异常" + e.getMessage());
                }
            }
            if (status == 0) {
                if (ds.getType() == 1) {
                    if (StringUtils.isNull(contractStrengthPrice.getId())) {
                        taskId = saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                                price, remark, nowDate, 0, 0);
                        if (taskId < 1) {
                            return -1;
                        }
                    } else {
                        taskId = saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                                price, remark, nowDate, 0, 1);
                        if (taskId < 1) {
                            return -1;
                        }
                    }
                }

                contractStrengthPrice.setContractId(contractId);
                contractStrengthPrice.setCreateTime(nowDate);
                contractStrengthPrice.setCreator(creator);
            } else {
                if (ds.getType() == 1) {
                    taskId = saveOrUpdateErp(jdbcTemplate, erpConId, strengthOrg.getErpId(), DateUtil.convertString(takeDate),
                            price, remark, nowDate, 1, 1);
                    if (taskId < 1) {
                        return -1;
                    }
                }

                contractStrengthPrice.setContractId(contractId);
                contractStrengthPrice.setUpdator(creator);
                contractStrengthPrice.setUpdateTime(nowDate);
            }
            contractStrengthPrice.setTakeTime(takeDate);
            tempList.add(contractStrengthPrice);
        }
        if (tempList == null || tempList.size() == 0)
            return -1;
        Integer code = saleContractStrengthPriceDao.saveBatch(tempList);
        if (code > 0) {
            return 0;
        }
        return -1;
    }

    /**
     * 生成标号价格
     * @param contractId 合同ID
     * @param strengthId 基础标号ID
     * @param special 特性
     * @return
     */
    public Double generatePriceV1(Long contractId, Long strengthId, String special) {
        Double price = 0.0;
        if (StringUtils.isAllParamNull(contractId, strengthId, special))
            return price;
        SaleContract contract = saleContractDao.selectById(contractId);
        if (contract == null || contract.getStatus().intValue() == 1)
            return price;
        Date nowDate = new Date();
        SaleContractStrengthPrice strengthPrice = saleContractStrengthPriceDao.findProPrice(contractId, strengthId, nowDate);
        if (strengthPrice == null || strengthPrice.getStatus() == 1)
            return price;
        BaseStrength baseStrength = baseStrengthDao.selectById(strengthId);
        price = strengthPrice.getPrice();
        if (contract.getPriceComposeType().intValue() != 0)
            return price;
        List<SaleStrengthSpecialPriceVo> specialList = saleStrengthSpecialPriceDao.findContractSpecial(null, contractId);
        if (specialList == null || specialList.size() == 0)
            return price;

        Double specialPrice = 0.0;
        for (int i = 0; i < specialList.size(); i++) {
            SaleStrengthSpecialPriceVo strengthSpecialPrice = specialList.get(i);
            if (special.indexOf(strengthSpecialPrice.getEquirement()) != -1) {//如果特性包含
                if (strengthSpecialPrice.getType().intValue() == SpecialPriceTypeEnum.GD.getCode().intValue()) {
                    specialPrice += strengthSpecialPrice.getPrice();
                } else {//如果是提级价
                    BaseStrengthLevel strengthLevel = baseStrengthLevelDao.findStrengthDetail(baseStrength.getStrength(), null, null);
                    if (strengthLevel == null)
                        continue;
                    //基础价格信息
                    Integer sort = strengthLevel.getSort() + strengthSpecialPrice.getLevel();
                    BaseStrengthLevel strengthLevel1 = baseStrengthLevelDao.findStrengthDetail(null, strengthLevel.getType(), sort);
                    if (strengthLevel1 == null) {
                        specialPrice += 0.0;
                    } else {//提级标号价格信息
                        SaleContractStrengthPrice strengthPrice1 = saleContractStrengthPriceDao.findProPrice(contractId, strengthLevel1.getStrengthId(), nowDate);
                        if (strengthPrice1 == null) {
                            specialPrice += 0.0;
                        } else {
                            Double tempAdjustPrice = StringUtils.convertDouble(strengthPrice1.getPrice() - strengthPrice.getPrice());
                            if (tempAdjustPrice < 0)//如果计算出来的价差错误,提级价变更为0
                                tempAdjustPrice = 0.0;
                            specialPrice += tempAdjustPrice;
                        }

                    }
                }
            }
        }
        price += specialPrice;
        return StringUtils.formatDouble(price, 2);
    }

    /**
     * 生成标号价格
     * @param contractId 合同ID
     * @param strengthId 基础标号ID
     * @param specialIds 合同特性ID 可多个(逗号隔开)
     * @return
     */
    public RestResultDto generatePrice(Long contractId, Long strengthId, String specialIds) {
        if (StringUtils.isAllParamNull(contractId, strengthId, specialIds))
            return RestResultDto.fail("参数错误");
        SaleContractVo contract = saleContractDao.selectById(contractId);
        if (contract == null || contract.getStatus().intValue() == 1)
            return RestResultDto.fail("合同不存在或已被禁用");
        if (contract.getPriceComposeType().intValue() != 0)
            return RestResultDto.fail("固定标号合同不提供组合标号");
        BaseStrength strength = baseStrengthDao.selectById(strengthId);
        if (strength == null || strength.getStatus().intValue() == 1)
            return RestResultDto.fail("基础标号不存在或已被禁用");
        Long levelId = strength.getLevelId();
        String baseLevel = strength.getLevel();
        String[] contractSpecialIds = specialIds.split(",");
        if (contractSpecialIds == null || contractSpecialIds.length == 0)
            return RestResultDto.fail("特性参数不存在");
        if (specialIds.substring(specialIds.length() - 1).equals(","))
            specialIds = specialIds.substring(0, specialIds.length() - 1);

        List<SaleStrengthSpecialPriceVo> specialList = saleStrengthSpecialPriceDao.findContractSpecial(specialIds, contractId);
        if (specialList == null || specialList.size() == 0)
            return RestResultDto.fail("合同特性信息不存在");

        SaleContractStrengthPrice strengthPrice = saleContractStrengthPriceDao.findTakeTime(contract.getOrgId(),
                contractId, strengthId, null);
        if (strengthPrice == null || strengthPrice.getStatus() == 1)
            return RestResultDto.fail("合同标号信息错误");
        Double price = strengthPrice.getPrice();
        Double specialPrice = 0.0;//调整价格
        String key = strength.getStrength();
        String level = strength.getStrength();
        if (key.indexOf("C") == 0) {
            if (key.length() > 3) //特性标号
                if (key.indexOf("C") == 0)
                    key = key.substring(0,3);
        } else if (key.indexOf("LC") == 0) {
            if (key.length() > 5) {//特性标号
                if (key.indexOf(".") != -1)
                    key = key.substring(0, 5);
            } else if (key.indexOf("M") == 0) {
                if (key.indexOf(".") != -1)
                    key = key.substring(0, 4);
            }
        }
        for (int i = 0; i < specialList.size(); i++) {
            SaleStrengthSpecialPriceVo strengthSpecialPrice = specialList.get(i);
            level += strengthSpecialPrice.getEquirement();//拼接特性名称
            if (strengthSpecialPrice.getType().intValue() == SpecialPriceTypeEnum.GD.getCode().intValue()) {
                specialPrice += strengthSpecialPrice.getPrice();
            } else {//如果是提级价
                BaseStrengthLevel strengthLevel = baseStrengthLevelDao.findStrengthDetail(key, null, null);
                if (strengthLevel == null)
                    continue;
                //基础价格信息
                Integer sort = strengthLevel.getSort() + strengthSpecialPrice.getLevel();
                BaseStrengthLevel strengthLevel1 = baseStrengthLevelDao.findStrengthDetail(null, strengthLevel.getType(), sort);
                if (strengthLevel1 == null) {
                    specialPrice += 0.0;
                } else {//提级标号价格信息
                    SaleContractStrengthPrice levelStrengthPrice = saleContractStrengthPriceDao.findTakeTime(contract.getOrgId(),
                            contractId, strengthLevel1.getStrengthId(), strengthPrice.getTakeTime());
                    if (levelStrengthPrice != null && levelStrengthPrice.getPrice() > 0) {
                        specialPrice += (levelStrengthPrice.getPrice() - price);//提级价
                    } else {
                        specialPrice += 0.0;
                    }
                }
            }
        }
        Date nowDate = new Date();
        price = StringUtils.formatDouble(price + specialPrice, 2);
        strength = baseStrengthDao.findExistStrength(level);
        if (strength == null) {
            strength = new BaseStrength(level, baseLevel, "", "", "",
                    0, 0, 0, "基础标号与特性组合新增标号", "系统管理员", nowDate, 2350.0,
                    "", "", "");
            strength.setLevelId(levelId);
            baseStrengthDao.insert(strength);
        }
        QueryWrapper<SaleContractStrengthPrice> priceQuery = new QueryWrapper<>();
        priceQuery.eq("status", 0);
        priceQuery.eq("contract_id", contractId);
        priceQuery.eq("strength_id", strength.getId());
        priceQuery.orderByDesc("id");
        List<SaleContractStrengthPrice> list1 = saleContractStrengthPriceDao.selectList(priceQuery);
        if (list1 != null && list1.size() > 0) {
            SaleContractStrengthPrice contractStrengthPrice = list1.get(0);
            if (contractStrengthPrice.getPrice().doubleValue() < 150) {
                contractStrengthPrice.setPrice(price);
                contractStrengthPrice.setRemark("组合标号更新单价");
                contractStrengthPrice.setUpdateTime(nowDate);
                contractStrengthPrice.setUpdator("系统管理员");
                saleContractStrengthPriceDao.updateById(contractStrengthPrice);
            }
            return RestResultDto.success(contractStrengthPrice);
        }

        DataSourceInfo ds = dataSourceInfoDao.queryDSByOriginId(contract.getOrgId());
        if (ds == null)
            return RestResultDto.fail("数据源不存在");
        JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
        BaseStrengthOrg strengthOrg = baseStrengthOrgDao.findByStrengthOrOrg(strength.getId(), contract.getOrgId());
        long taskId = 0l;
        if (strengthOrg == null ) {
            if (ds.getType() == 1) {
                String strengthSql = "insert into Sys_ConcreteStrength_T (Sys_Dept_ID,CompressiveStrength,Anti_permeabilityLevel,\n" +
                        "  BendingLevel,Anti_freezeLevel,MaterialRequirements,TechRequirements,StrengthLevel,Remarks,CreatorID,\n" +
                        "  CreationTime,IsValid,Dosage,IsNormal) " +
                        "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

                Object[] params = {1, strength.getLevel(), strength.getPermeability(), strength.getBending(), strength.getFreeze(),
                        strength.getMaterialRequirement(), strength.getTechnologyRequirement(), strength.getLevel(), "", 1,
                        DateUtil.convertString(nowDate), 1, strength.getDosage(), 0};

                KeyHolder keyHolder = new GeneratedKeyHolder();
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(strengthSql, new String[]{"ID"});
                        for (int i = 0; i < params.length; i++) {
                            ps.setObject(i + 1, params[i]);
                        }
                        return ps;
                    }
                }, keyHolder);
                taskId = keyHolder.getKey().longValue();
                if (taskId < 1) {
                    return RestResultDto.fail("添加ERP标号错误");
                }
            }

            strengthOrg = new BaseStrengthOrg(contract.getOrgId(), taskId, strength.getId(), 0, "组合标号创建", "系统管理员", nowDate);
            strengthOrg.setTransportType(strength.getTransportType());
            baseStrengthOrgDao.insert(strengthOrg);
            try {
                sendLabMessage(contract, strength.getStrength(), DateUtil.convertString(nowDate), "微信订单客户申请下单", "系统管理员");
            } catch (Exception e) {
                log.error("推送新增标号预警异常" + e.getMessage());
            }
        }
        Long erpId = null;
        if (!StringUtils.isNull(contract.getErpid()) && contract.getErpid() > 0) {
            erpId = contract.getErpid();
        } else {
            if (ds.getType() == 1) {
                String contractSql = "select top 1 * from market_contract_t " +
                        " where isvalid = 1 and U_Code = '" + contract.getCode() + "' order by id desc";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(contractSql);
                if (list == null || list.size() == 0)
                    return RestResultDto.fail("ERP合同列表为空");
                erpId = StringUtils.convertLong(list.get(0).get("ID"));
            }
        }

        if (ds.getType() == 1) {
            taskId = saveOrUpdateErp(jdbcTemplate, erpId, strengthOrg.getErpId(), DateUtil.convertString(strengthPrice.getTakeTime()),
                    price, "系统生成组合标号", nowDate, 0,0);
        }

        SaleContractStrengthPrice newStrengthPrice = new SaleContractStrengthPrice(contract.getOrgId(), contractId, strength.getId(),
                price, strengthPrice.getTakeTime(), 0, "系统生成组合标号", "系统管理员", nowDate);
        Integer code = saleContractStrengthPriceDao.insert(newStrengthPrice);
        newStrengthPrice.setStrength(strength.getStrength());
        if (code > 0) {
            newStrengthPrice.setErpStrengthId(strengthOrg.getErpId());
            return RestResultDto.success(newStrengthPrice);
        }

        return RestResultDto.fail("添加失败~！");
    }

	@Override
	public SaleContractStrengthPrice findMaxPrice(Long conId) {
		if (conId == null) {
			return null;
		}
		Date nowDate = new Date();
		SaleContractStrengthPrice conPrice = saleContractStrengthPriceDao.findMaxPrice(conId, nowDate);
		return conPrice;
	}

    /**
     * 查询合同中是否存在该标号
     * @param contractId
     * @param strengthId
     * @return
     */
    public SaleContractStrengthPrice findExistPrice(Long contractId, Long strengthId) {
        if (StringUtils.isAllParamNull(contractId, strengthId))
            return null;
        QueryWrapper<SaleContractStrengthPrice> query = new QueryWrapper<>();
        query.eq("status", 0);
        query.eq("contract_id", contractId);
        query.eq("strength_id", strengthId);
        query.orderByDesc("id");
        List<SaleContractStrengthPrice> priceList = saleContractStrengthPriceDao.selectList(query);
        if (priceList == null || priceList.size() == 0)
            return null;
        return priceList.get(0);
    }

	/**
     * 保存或更新ERP砼单价
     * @param erpConId
     * @param erpStrengthId
     * @param takeTime
     * @param price
     * @param remark
     * @return
     */
    private Long saveOrUpdateErp(JdbcTemplate jdbcTemplate, Long erpConId, Long erpStrengthId, String takeTime,
                                 Double price, String remark, Date nowDate, Integer status, Integer type) {
        Integer isValid = 1;
        if (status == 1)
            isValid = 0;
        String sql = "select top 1 * from Market_Contract_Price_T where IsValid = 1 and Market_Contract_ID = "
                + erpConId + " and Sys_ConcreteStrength_ID = " + erpStrengthId + " and StartDatetime = '" + takeTime + "'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (list == null || list.size() == 0) {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            String addSql = "INSERT INTO Market_Contract_Price_T (Market_Contract_ID,Sys_ConcreteStrength_ID,StartDatetime," +
                    "Price,Remarks,IsVerify,CreatorID,CreationTime,ReviseID,ReviseTime,IsValid)\n" +
                    "values (?,?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {erpConId, erpStrengthId, takeTime,price,remark,1,1,DateUtil.convertString(nowDate),1,
                    DateUtil.convertString(nowDate),isValid};
            jdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(addSql, new String[]{"ID"});
                    for (int i = 0; i < params.length; i++) {
                        ps.setObject(i + 1, params[i]);
                    }
                    return ps;
                }
            }, keyHolder);
            long taskId = keyHolder.getKey().longValue();
            return taskId;
        } else {
            Long id = StringUtils.convertLong(list.get(0).get("ID"));
            String updateSql = "update Market_Contract_Price_T set Market_Contract_ID = " + erpConId + ",Sys_ConcreteStrength_ID ="
                    + erpStrengthId + ",StartDatetime='" + takeTime + "',Price=" + price + ",Remarks='" + remark
                    + "',ReviseTime='" + DateUtil.convertString(nowDate) + "',isValid= " + isValid + " where id = " + id;
            jdbcTemplate.update(updateSql);
            return id;
        }
    }

    /**
     * 技术部特性标号推送预警
     * @param contract
     * @param strength
     * @param takeTime
     * @param remark
     * @param creator
     */
    private void sendLabMessage(SaleContractVo contract, String strength, String takeTime, String remark, String creator) {
        String touser = "lucky|1lt1556|";
        String toname = "万强|罗涛|";
        String message = "";
        Date nowDate = new Date();
        String title = "";//推送标题
        String orgName = "";
        if (!StringUtils.isNull(contract.getOrgId())) {
            SysOrigin origin = originDao.selectById(contract.getOrgId());
            if (origin != null)
                orgName = origin.getOriginName();
        }
        message = "【工程新增标号预警通知】 " + orgName + " 合同编号:" + contract.getCode();
        message += "\n工程名称:" + contract.getClientName() + "[" + contract.getName() + "]";
        message += "\n生效时间:" + takeTime;
        message += "\n标号:" + strength + "。";
        if (!StringUtils.isNull(remark))
            message += "备注:" + remark;
        if (!StringUtils.isNull(creator)) {
            message += "\n操作人:" + creator;
        }
        message += "\n操作时间:" + DateUtil.convertString(nowDate);
        message += "\n请技术与研发部核实是否有供应资质。若有疑问,请尽快联系销售部、生产运营部相关人员协商处理。";

        List<Map<String, Object>> list = userPositionDao.hasGeneralManager(contract.getOrgId(), "资料员", "技术员");
        List<Map<String, Object>> list1 = userPositionDao.hasGeneralManager(contract.getOrgId(), "技术与研发部主任", "技术与研发部副主任");
        List<Map<String, Object>> list2 = userPositionDao.hasGeneralManager(contract.getOrgId(), "资料组长", "资料组长");
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> temp = list.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }
        if (list1 != null && list1.size() > 0) {
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> temp = list1.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }
        if (list2 != null && list2.size() > 0) {
            for (int i = 0; i < list2.size(); i++) {
                Map<String, Object> temp = list2.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }
        toname = toname.substring(0, toname.length() - 1);
        touser = touser.substring(0, touser.length() - 1);
        SysMessageRecord record = new SysMessageRecord(touser, toname, "", WechatOaGroupApi.corpID, "", contract.getOrgId(),
                "", 1, 1, title, "",
                message, "", 1, 0, "", "", nowDate);
        messageRecordDao.insert(record);
        WechatOaGroupApi.sendTextMessage(WechatOaGroupApi.corpID, WechatOaGroupApi.corpSecret,
                WechatOaGroupApi.agentId, touser, message);

    }

    private void sendMessage(SaleContractVo contract, Long strengthId, String takeTime, Double price, Double newPrice,
                             Double taxPrice, Double taxPewPrice,String remark, String creator, Integer updateType) {
        String touser = "lucky|1lt1556|";
        String toname = "万强|罗涛|";
        String message = "";
        Date nowDate = new Date();
        String title = "";//推送标题
        String orgName = "";
        if (!StringUtils.isNull(contract.getOrgId())) {
            SysOrigin origin = originDao.selectById(contract.getOrgId());
            if (origin != null)
                orgName = origin.getOriginName();
        }
        if (updateType == 0) {
            message = "【工程砼单价新增通知】 " + orgName + " 编号:" + contract.getCode();
            message += "\n工程名称:" + contract.getClientName() + "[" + contract.getName() + "]";
            message += "\n生效时间:" + takeTime;
            BaseStrength baseStrength = baseStrengthDao.selectById(strengthId);
            if (baseStrength == null)
                return;
            message += "\n标号:" + baseStrength.getStrength() + ",单价:" + price + "元。";
            message += "\n含税单价:" + taxPrice + "元。";
            if (!StringUtils.isNull(remark))
                message += "备注:" + remark;
        } else if (updateType == 1){
            message = "【工程砼单价变更通知】 " + orgName + " 编号:" + contract.getCode();
            message += "\n工程名称:" + contract.getClientName() + "[" + contract.getName() + "]";
            if (StringUtils.isNull(takeTime)) {
                message += "\n生效时间:" + takeTime;
            }
            BaseStrength baseStrength = baseStrengthDao.selectById(strengthId);
            if (baseStrength == null)
                return;
            message += "\n标号:" + baseStrength.getStrength() + ",单价:" + price + "元 -> " + newPrice + "元。";
            message += "\n含税单价:" + StringUtils.formatDouble(taxPrice,2) + "元 -> " + taxPewPrice + "元。";
            if (!StringUtils.isNull(remark))
                message += "备注:" + remark;
        }
        if (!StringUtils.isNull(creator)) {
            message += "\n操作人:" + creator;
        }
        message += "\n操作时间:" + DateUtil.convertString(nowDate);

        List<Map<String, Object>> list = userPositionDao.hasGeneralManager(contract.getOrgId(), "销售内业", "信控专员");
        if (!StringUtils.isNull(contract.getSales())) {
            SysUser user = userDao.queryByName(contract.getSales());
            if (user != null && toname.indexOf(user.getName()) == -1) {
                toname += user.getName() + "|";
                touser += user.getUsername() + "|";
            }
        }
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> temp = list.get(i);
                String name = StringUtils.convertString(temp.get("name"));
                if (!StringUtils.isNull(name) && toname.indexOf(name) == -1) {
                    toname += temp.get("name") + "|";
                    touser += temp.get("username") + "|";
                }
            }
        }

        toname = toname.substring(0, toname.length() - 1);
        touser = touser.substring(0, touser.length() - 1);
        SysMessageRecord record = new SysMessageRecord(touser, toname, "", WechatOaGroupApi.corpID, "", contract.getOrgId(),
                "", 1, 1, title, "",
                message, "", 1, 0, "", "", nowDate);
        messageRecordDao.insert(record);
        WechatOaGroupApi.sendTextMessage(WechatOaGroupApi.corpID, WechatOaGroupApi.corpSecret,
                WechatOaGroupApi.agentId, touser, message);

    }

}
